<template>
	<div id="formBatch">
		<h1>批次基础信息</h1>
		<el-form ref="phase_time"  label-width="80px" >
			<el-form-item
      label-width="140px"
      label="批次名称:"
      :rules="[{required:true}]"
      >
				<el-input v-model="phase_time.phase_name"></el-input>
			</el-form-item>
			<el-form-item
      label-width="140px"
      label="所属单位："
      :rules="[{required:true}]"
      >
				<el-input v-model="batch.company"></el-input>
			</el-form-item>
			<el-row>
				<el-col :span="12">
					<el-form-item
          label-width="140px"
          label="批次级别："
          :rules="[{required:true}]"
          >
						<el-cascader v-model="batch.level_id" :options="levelOptions" :show-all-levels="false"
							:props="{ value:'levelId', label:'levelName'}">
						</el-cascader>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label-width="140px" id="switchExpert" label="专家设置：">
						<el-switch v-model="switchExpert" @change="emptyTime"> </el-switch>
					</el-form-item>
				</el-col>
			</el-row>

			<el-form-item
      label-width="140px"
      label="项目分类："
      :rules="[{required:true}]"
      >
				<div>
					<el-tag :key="tag" v-for="tag in classifyTags" closable :disable-transitions="false"
						@close="handleClose(tag)">
						{{ tag }}
					</el-tag>
					<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
						size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
					</el-input>
					<el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新分类</el-button>
				</div>
			</el-form-item>
			<el-form-item
      label-width="140px"
      label="最大主持数："
      :rules="[{required:true}]"
      >
				<el-input v-model="batch.max_host"></el-input>
			</el-form-item>
			<el-form-item
      label-width="140px"
      label="最大参与数："
      :rules="[{required:true}]"
      >
				<el-input v-model="batch.max_participants"></el-input>
			</el-form-item>
			<el-form-item
      label-width="140px"
      label="教师申报时间："
      :rules="[{required:true}]"
      >
				<DateTimeRange :before.sync="date" :start.sync="phase_time.phase_teacher_start"
					:end.sync="phase_time.phase_teacher_end" :last.sync="phase_time.phase_department_start">
				</DateTimeRange>
			</el-form-item>
			<el-form-item
      label-width="140px"
      label="院级审核时间："
      :rules="[{required:true}]"
      >
				<DateTimeRange :before.sync="phase_time.phase_teacher_end"
					:start.sync="phase_time.phase_department_start" :end.sync="phase_time.phase_department_end"
					:last.sync="phase_time.phase_school_first_start"></DateTimeRange>
			</el-form-item>
			<el-form-item
      label-width="140px"
      label="校级审核时间："
      :rules="[{required:true}]"
      >
				<DateTimeRange :before.sync="phase_time.phase_department_end"
					:start.sync="phase_time.phase_school_first_start" :end.sync="phase_time.phase_school_first_end"
					:last.sync="phase_time.phase_expert_start"></DateTimeRange>
			</el-form-item>
			<el-form-item
      label-width="140px"
      :rules="[{required:true}]"
      label="专家审核时间："
      v-if="switchExpert"
      >
				<DateTimeRange :before.sync="phase_time.phase_school_first_end"
					:start.sync="phase_time.phase_expert_start" :end.sync="phase_time.phase_expert_end"
					:last.sync="phase_time.phase_school_second_start"></DateTimeRange>
			</el-form-item>
			<el-form-item
      label-width="140px"
      label="校级复审时间："
      :rules="[{required:true}]"
      v-if="switchExpert"
      >
				<DateTimeRange :before.sync="phase_time.phase_expert_end"
					:start.sync="phase_time.phase_school_second_start" :end.sync="phase_time.phase_school_second_end"
					:last.sync="last"></DateTimeRange>
			</el-form-item>
			<el-form-item label-width="140px" label="提醒：" v-if="
          (switchExpert && phase_time.phase_school_second_end != '') ||
          (!switchExpert && phase_time.phase_school_first_end != '')
        ">
				<el-row>
					<el-col :span="18">
						<DateTimeRange :before.sync="alter" :start.sync="batch.middle_time" :end.sync="batch.post_time"
							:last.sync="last" :startTip.sync="startTip" :endTip.sync="endTip"></DateTimeRange>
					</el-col>
					<el-col :span="6">
						<el-switch v-model="switchAlert" @change="switchAlertFun">
						</el-switch>
					</el-col>
				</el-row>
			</el-form-item>
			<el-form-item id="btn">
				<el-button type="primary" @click="submitForm()">保存</el-button>
				<el-button @click="goBatch">退出</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>
<script>
	import DateTimeRange from "@/components/DateTimeRange";

	export default {
		components: {
			DateTimeRange
		},
		data() {
			return {
				tempMaxParticipants:"",
				tempMaxhost:"",
				tempClassifyTag:[],
				batchInfo: {},
				date: Date.now() - 24 * 60 * 60 * 1000,
				startTip: '中期设置提醒时间',
				endTip: '结项设置提醒时间',
				last: "",
				batch_id: "",
				a: "5",
				batch: {
					level_id:"",
					level_name: "",
					company: "",
					max_host: "",
					max_participants: "",
					middle_time: "",
					post_time: "",
				},
				phase_time: {
					phase_id: "",
					phase_name: "",
					phase_teacher_start: "",
					phase_teacher_end: "",
					phase_department_start: "",
					phase_department_end: "",
					phase_school_first_start: "",
					phase_school_first_end: "",
					phase_expert_start: "",
					phase_expert_end: "",
					phase_school_second_start: "",
					phase_school_second_end: "",
					score_path: "",
					path: "",
					type: 1
				},
				levelOptions: [],
				switchExpert: true,
				switchAlert: false,
				alter: "",
				classifyTags: [],
				inputVisible: false,
				inputValue: "",
			};
		},
		mounted() {
			this.getAllLevel();
			this.getDataAxios();
			this.getConfirmDate();
		},
		methods: {
			test(){
				console.log("专家开始:"+this.phase_time.phase_expert_start)
			},
			changeDetSelect(key,treeData){//根据id回显级联选择器
			let arr = []; // 在递归时操作的数组
			let returnArr = []; // 存放结果的数组
			let depth = 0; // 定义全局层级
			// 定义递归函数
			function childrenEach(childrenData, depthN) {
			    for (var j = 0; j < childrenData.length; j++) {
			        depth = depthN; // 将执行的层级赋值 到 全局层级
			        arr[depthN] = (childrenData[j].levelId);
			        if (childrenData[j].levelId == key) {
			            returnArr = arr.slice(0, depthN+1); //将目前匹配的数组，截断并保存到结果数组，
			            break
			        } else {
			            if (childrenData[j].children) {
			                depth ++;
			                childrenEach(childrenData[j].children, depth);
			            }
			        }
			    }
			    return returnArr;
			}
			return childrenEach(treeData, depth);
			},
			//提交
			submitForm() {
        var numReg = /^[0-9]*$/
        var numRe = new RegExp(numReg)
        if(this.phase_time.phase_name==''){
          this.$message({
          	showClose: true,
          	message: "批次名称不能为空！",
          	type: "warning",
          	center: true,
          	offset: (screen.height / 2) - 200,
            duration:2000
          })
          return
        }

        if(this.batch.company==''){
          this.$message({
          	showClose: true,
          	message: "所属单位不能为空！",
          	type: "warning",
          	center: true,
          	offset: (screen.height / 2) - 200,
            duration:2000
          })
          return
        }
        if(this.classifyTags.length==0){
          this.$message({
          	showClose: true,
          	message: "项目分类不能为空！",
          	type: "error",
          	center: true,
          	offset: (screen.height / 2) - 200,
            duration:2000
          })
          return
        }

        if (!numRe.test(this.batch.max_host)) {
          this.$message({
            type: 'warning',
            message: '最大主持数必须是数字！ ',
            offset:screen.height/2-200,
            showClose: true,
            center:true,
            duration:2000
          })
          return false
        }

        if (this.batch.max_host >=1000) {
        	this.$message({
        		showClose: true,
        		message: '最大主持数请勿大于1000！',
        		type: 'warning',
        		center:true,
        		offset:(screen.height/2)-80
        	});
        	return
        }

				if(this.batch.max_host<this.tempMaxhost){
					this.$message({
						showClose: true,
						message: "已有教师主持数大于此主持数，请重新设置！",
						type: "error",
						center: true,
						offset: (screen.height / 2) - 200
					})
					return
				}



        if (!numRe.test(this.batch.max_participants)) {
          this.$message({
            type: 'warning',
            message: '最大参与数必须是数字！ ',
            offset:screen.height/2-200,
            showClose: true,
            center:true,
            duration:2000
          })
          return false
        }

        if (this.batch.max_participants >=1000) {
        	this.$message({
        		showClose: true,
        		message: '最大参与数请勿大于1000！',
        		type: 'warning',
        		center:true,
        		offset:(screen.height/2)-80
        	});
        	return
        }

        // if(this.batch.max_participants<this.tempMaxParticipants){
        //   console.log(this.tempMaxParticipants)
        // 	this.$message({
        // 		showClose: true,
        // 		message: "已有教师参与数大于此参与数，请重新设置！！",
        // 		type: "error",
        // 		center: true,
        // 		offset: (screen.height / 2) - 200
        // 	})
        // 	return
        // }

        if(this.phase_time.phase_teacher_start=="" || this.phase_time.phase_teacher_end==""){
          this.$message({
            type: 'warning',
            message: '教师申报时间不能为空！ ',
            duration: 2000,
            offset:screen.height/2-200,
            showClose: true,
            center:true,
          })
          return false
        }

        if(this.phase_time.phase_department_start=="" || this.phase_time.phase_department_end==""){
          this.$message({
            type: 'warning',
            message: '院级审核时间不能为空！ ',
            duration: 2000,
            offset:screen.height/2-200,
            showClose: true,
            center:true,
          })
          return false
        }

        if(this.phase_time.phase_school_first_start=="" || this.phase_time.phase_school_first_end==""){
          this.$message({
            type: 'warning',
            message: '校级审核时间不能为空！ ',
            duration: 2000,
            offset:screen.height/2-200,
            showClose: true,
            center:true,
          })
          return false
        }
        if(this.switchExpert==true){
          if(this.phase_time.phase_expert_start=="" || this.phase_time.phase_expert_end==""){
            this.$message({
              type: 'warning',
              message: '专家审核时间不能为空！ ',
              duration: 2000,
              offset:screen.height/2-200,
              showClose: true,
              center:true,
            })
            return false
          }

          if(this.phase_time.phase_school_second_start=="" || this.phase_time.phase_school_second_end==""){
            this.$message({
              type: 'warning',
              message: '校级复审时间不能为空！ ',
              duration: 2000,
              offset:screen.height/2-200,
              showClose: true,
              center:true,
            })
            return false
          }
        }

				this.editBatchAxios()
			},
			getConfirmDate(){
				this.$api.batch
				.getProjectClassification({ //查询该批次下项目的类别信息
					batch_id: this.batch_id
				}).then((response) => {
          console.log(response)
					this.tempClassifyTag = response.data.data
				})

				this.$api.batch.selectMaxHost({//查询批次下最大主持数
					batch_id: this.batch_id
				}).then((response)=>{
					this.tempMaxhost=response.data.data
				})

				this.$api.batch.selectMaxParticipants({//查询批次下最大参与数
					batch_id: this.batch_id
				}).then((response)=>{
					console.log(response)
					this.tempMaxParticipants=response.data.data
					console.log(this.tempMaxParticipants)
				})
			}
			,
			goBatch() {
				this.$router.push({
					path: "/Batch"
				})
			},
			getTreeData(data) {
				// 循环遍历json数据
				for (var i = 0; i < data.length; i++) {

					if (data[i].children.length < 1) {
						// children若为空数组，则将children设为undefined
						data[i].children = undefined;
					} else {
						// children若不为空数组，则继续 递归调用 本方法
						this.getTreeData(data[i].children);
					}
				}
				return data;
			},
			editBatchAxios() { //修改批次方法
            if(this.phase_time.phase_expert_start==null){
              this.phase_time.phase_expert_start='';
              this.phase_time.phase_expert_end='';
              this.phase_time.phase_school_second_start='';
              this.phase_time.phase_school_second_end='';
            }
				this.$api.batch.editBatch({
					batchId: this.batch_id,
					batchName: this.phase_time.phase_name,
					classifyId: this.batchInfo.classifyId,
					classifyName: this.classifyTags,
					company: this.batch.company,
					// levelId: this.batch.level_id[this.batch.level_id.length - 1],
					levelId: this.batch.level_id,
					levelName: "",
					maxHost: this.batch.max_host,
					maxParticipants: this.batch.max_participants,
					phaseDepartmentEnd: this.phase_time.phase_department_end,
					phaseDepartmentStart: this.phase_time.phase_department_start,
					phaseId: this.batchInfo.phaseId,
					phaseTeacherEnd: this.phase_time.phase_teacher_end,
					phaseTeacherStart: this.phase_time.phase_teacher_start,
					middleTime: this.batch.middle_time,
					phaseExpertEnd: this.phase_time.phase_expert_end,
					phaseExpertStart: this.phase_time.phase_expert_start,
					phaseSchoolFirstEnd: this.phase_time.phase_school_first_end,
					phaseSchoolFirstStart: this.phase_time.phase_school_first_start,
					phaseSchoolSecondEnd: this.phase_time.phase_school_second_end,
					phaseSchoolSecondStart: this.phase_time.phase_school_second_start,
					postTime: this.batch.post_time,
					type: 1
				}).then(
					(response) => {
						console.log(response)
						if (response.data.code == 200) {
							this.$message({
								showClose: true,
								message: "批次修改成功！",
								type: "success",
								center: true,
								offset: (screen.height / 2) - 200
							});
						} else {
							this.$message({
								showClose: true,
								message: "批次修改失败！",
								type: "error",
								center: true,
								offset: (screen.height / 2) - 200
							})
						}
					}
				)
				console.log(this.batchInfo)
			},
			//获取数据
			getDataAxios() {
				this.batch_id = this.$route.query.batch_id;
				// console.log(this.batch_id)
				if (this.batch_id != undefined) {}
				this.$api.batch.getAllBatch().then((responsive) => {
					this.batchInfo = responsive.data.data.find((item) => {
						return item.batchId == this.batch_id
					})
					console.log(this.batchInfo)
					if (this.batchInfo.phaseExpertStart == null || this.batchInfo.phaseExpertStart == '') {
						this.switchExpert = false
					}
					//赋值给页面
					this.phase_time.phase_name = this.batchInfo.batchName
					this.batch.company = this.batchInfo.company
					// this.batch.level_id = this.changeDetSelect(this.batchInfo.levelId,this.levelOptions)

					this.batch.level_id = this.batchInfo.levelId
					console.log(this.batch.level_id)
					this.classifyTags = this.batchInfo.classifyName.split(',')
					this.batch.max_host = this.batchInfo.maxHost
					this.batch.max_participants = this.batchInfo.maxParticipants
					this.phase_time.phase_teacher_start = this.batchInfo.phaseTeacherStart
					this.phase_time.phase_teacher_end = this.batchInfo.phaseTeacherEnd
					this.phase_time.phase_department_start = this.batchInfo.phaseDepartmentStart
					this.phase_time.phase_department_end = this.batchInfo.phaseDepartmentEnd
					this.phase_time.phase_school_first_start = this.batchInfo.phaseSchoolFirstStart
					this.phase_time.phase_school_first_end = this.batchInfo.phaseSchoolFirstEnd
					this.phase_time.phase_expert_start = this.batchInfo.phaseExpertStart
					// this.phase_time.phase_expert_start = this.batchInfo.phaseExpertStart
					this.phase_time.phase_expert_end = this.batchInfo.phaseExpertEnd
					this.phase_time.phase_school_second_start = this.batchInfo.phaseSchoolSecondStart
					this.phase_time.phase_school_second_end = this.batchInfo.phaseSchoolSecondEnd


					if (this.batchInfo.middleTime == "" || this.batchInfo.middleTime == null) {
						this.switchAlert = false
					} else {
						this.switchAlert = true
						this.batch.middle_time = this.batchInfo.middleTime
						this.batch.post_time = this.batchInfo.postTime
					}

				})
			},
			getAllLevel() { //获得批次级别并填充
				this.$api.Level.getAllLevel()
					.then((response) => {
						console.log(response)
						this.levelOptions = this.getTreeData(response.data.data)
						for(let i=0;i<this.levelOptions.length;i++){
							delete this.levelOptions[i].children
						}
						console.log(this.levelOptions)
					})
			},
			//清空专家相关时间
			emptyTime() {
				this.phase_time.phase_expert_start = "";
				this.phase_time.phase_expert_end = "";
				this.phase_time.phase_school_second_start = "";
				this.phase_time.phase_school_second_end = "";
				this.emptyAlert();
			},
			emptyAlert() {
				this.alter = "";
				this.switchAlert = false;
				this.batch.middle_time = "";
				this.batch.post_time = "";
				console.log(this.phase_time)
			},
			switchAlertFun() {
				if (this.switchAlert) {
					if (this.switchExpert) {
						this.alter = this.phase_time.phase_school_second_end;
					} else {
						this.alter = this.phase_time.phase_school_first_end;
					}
				} else this.alter = "";
			},
			handleClose(tag) {
				for (let i = 0; i < this.tempClassifyTag.length; i++) {
					if (this.tempClassifyTag[i] == tag) {
						this.$message({
							type: 'error',
							message: '该分类内已有项目，不能删除!',
							center: true,
							offset: (screen.height / 2) - 200
						});
						return
					}
				}
				this.classifyTags.splice(this.classifyTags.indexOf(tag), 1);
				this.$message({
					type: 'success',
					message: '删除成功!',
					center: true,
					offset: (screen.height / 2) - 200
				});

			},

			showInput() {
				this.inputVisible = true;
				this.$nextTick((_) => {
					this.$refs.saveTagInput.$refs.input.focus();
				});
			},

			handleInputConfirm() {
				let inputValue = this.inputValue.trim();
				if (inputValue) {
					for (let i = 0; i < this.classifyTags.length; i++) {
						if (this.classifyTags[i] == inputValue) {
							this.$message({
								showClose: true,
								message: "分类名已存在",
								type: "error",
								center: true,
								offset: (screen.height / 2) - 200
							});
							return;
						}
					}
					this.classifyTags.push(inputValue);
				}
				this.inputVisible = false;
				this.inputValue = "";
			}

		},
		//对象内成员监听映射
		computed: {
			phase_teacher_start() {
				return this.phase_time.phase_teacher_start;
			},
			phase_teacher_end() {
				return this.phase_time.phase_teacher_end;
			},
			phase_department_start() {
				return this.phase_time.phase_department_start;
			},
			phase_department_end() {
				return this.phase_time.phase_department_end;
			},
			phase_school_first_start() {
				return this.phase_time.phase_school_first_start;
			},
			phase_school_first_end() {
				return this.phase_time.phase_school_first_end;
			},
			phase_expert_start() {
				return this.phase_time.phase_expert_start;
			},
			phase_expert_end() {
				return this.phase_time.phase_expert_end;
			},
			phase_school_second_start() {
				return this.phase_time.phase_school_second_start;
			},
			phase_school_second_end() {
				return this.phase_time.phase_school_second_end;
			},
		},
		//对象内成员监听
		watch: {
			phase_teacher_start(newV, oldV) {
				console.log(newV);
				this.phase_time.phase_teacher_start = newV;
			},
			phase_teacher_end(newV, oldV) {
				console.log(newV);
				this.phase_time.phase_teacher_end = newV;
			},
			phase_department_start(newV, oldV) {
				this.phase_time.phase_department_start = newV;
				console.log(this.phase_time.phase_department_start);
			},
			phase_department_end(newV, oldV) {
				this.phase_time.phase_department_end = newV;
			},
			phase_school_first_start(newV, oldV) {
				this.phase_time.phase_school_first_start = newV;
			},
			phase_school_first_end(newV, oldV) {
				if (newV == "") this.emptyAlert();
				this.phase_time.phase_school_first_end = newV;
			},
			phase_expert_start(newV, oldV) {
				this.phase_time.phase_expert_start = newV;
			},
			phase_expert_end(newV, oldV) {
				this.phase_time.phase_expert_end = newV;
			},
			phase_school_second_start(newV, oldV) {
				this.phase_time.phase_school_second_start = newV;
			},
			phase_school_second_end(newV, oldV) {
				if (newV == "") this.emptyAlert();
				this.phase_time.phase_school_second_end = newV;
			},
			switchAlert() {
				if (!this.switchAlert) this.emptyAlert();
			},
			value() {
				console.log(this.value);
			},
		},
	};
</script>
<style scoped>
	h1 {
		font-size: 30px;
		text-align: center;
	}

	.el-switch {
		padding-top: 10px;
	}

	#formBatch {
		width: 800px;
		position: relative;
		left: 50%;
		transform: translateX(-50%);
	}

	#btn {
		position: absolute;
		left: 45%;
		transform: translateX(-50%);
	}


	#switchExpert .el-switch {
		position: absolute;
		left: 30%;
		transform: translateX(-50%);
	}

	#btn {
		padding-bottom: 30px;
	}

	.el-tag+.el-tag {
		margin-left: 10px;
	}

	.button-new-tag {
		margin-left: 10px;
		height: 32px;
		line-height: 30px;
		padding-top: 0;
		padding-bottom: 0;
	}

	.input-new-tag {
		width: 90px;
		margin-left: 10px;
		vertical-align: bottom;
	}
</style>
